package com.ruoyi.web.controller.file;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;

@Component
public class UploadUtil {

    @Value("${app.upload-path}")
    private String baseUrl;

    @Value("${app.fileUrl}")
    private String fileUrl;

    /**
     * 文件上传
     * 获取文件名称，把文件存储到D:\picturePath路径下
     * @param files
     * @return
     * @throws Exception
     */
    public AjaxResult uploadImages(MultipartFile files[]) throws Exception {
        String url;
        try {
            ArrayList<String> urlList = new ArrayList<>();;
            for (int i = 0; i < files.length; i++) {
                MultipartFile multipartFile = files[i];
                String fileName = multipartFile.getOriginalFilename();
                String realPath = baseUrl;
                System.out.println("realPath==>" + realPath);

                //创建存放的目录
                File dir = new File(realPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File file = new File(realPath, fileName);
                multipartFile.transferTo(file);
                url = fileUrl + fileName;
                System.out.println("url==>" + url);
                urlList.add(url);
            }
            return new AjaxResult(200, "文件传送成功", urlList);
        } catch (Exception e) {
            return new AjaxResult(500, "文件传送失败", null);
            //return new CommonResult(2001, "数据库执行有异常", null);
        }
        // return new CommonResult(200, "添加成功", url);
    }
}


